package com.yys.huarongdao;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.yys.huarongdao.application.MyApplication;
import com.yys.huarongdao.dao.MySQLiteOpenHelper;
import com.yys.huarongdao.utils.BgmUtil;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_account;
    private EditText et_pwd;
    private Button but_login;
    private Button but_register;
    private CheckBox cb_remenberPwd;
    private MySQLiteOpenHelper sqLiteOpenHelper;
    private Cursor cursor;
    private ProgressDialog bar;
    private final static int PROGRESS_MAXVALUE=100;
    private LoginAndRegisterAsyncTask loginAsyncTask;
    private LoginAndRegisterAsyncTask registerAsyncTask;
    private final static int LOGIN_TASK = 0;
    private final static int REGISTER_TASK = 1;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        //设置全屏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        bindView();
        sqLiteOpenHelper = new MySQLiteOpenHelper(this,"huarongdao.db",null,1);
//        //初始化背景音乐
//        BgmUtil.initBgm(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(registerAsyncTask!=null&&!registerAsyncTask.isCancelled()){
            registerAsyncTask.cancel(true);
        }
        if(loginAsyncTask!=null&&!loginAsyncTask.isCancelled()){
            loginAsyncTask.cancel(true);
        }
        if(bar!=null)
            bar.dismiss();
    }

    private void bindView(){
        et_account = findViewById(R.id.et_account);
        et_pwd = findViewById(R.id.et_pwd);
        but_login = findViewById(R.id.but_login);
        but_register = findViewById(R.id.but_register);
        cb_remenberPwd = findViewById(R.id.cb_rememberPwd);

        but_login.setOnClickListener(this);
        but_register.setOnClickListener(this);

        SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("remember_pwd",MODE_PRIVATE);
        String account = sharedPreferences.getString("account","");
        String pwd = sharedPreferences.getString("pwd","");
        et_account.setText(account);
        et_pwd.setText(pwd);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.but_login:
                try {
                    userLogin();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.but_register:
                userRegister();

        }
    }

    private void userRegister() {
        /**
         * 用户注册
         * 1、判断输入是否为空
         * 2、判断用户账号是否已存在
         * 3、添加用户账号数据
         */
        String account =et_account.getText().toString();
        String pwd  = et_pwd.getText().toString();
        if(account.isEmpty()||pwd.isEmpty()){
            Toast.makeText(this,"账号密码不可以为空！",Toast.LENGTH_LONG).show();
            return;
        }
        //开启异步注册
        registerAsyncTask = new LoginAndRegisterAsyncTask();
        registerAsyncTask.setTaskType(REGISTER_TASK);
        registerAsyncTask.execute(0,account,pwd);
    }

    private void userLogin() throws InterruptedException {
        /**
         * 用户登录
         * 1、判断输入是否为空
         * 2、从数据库中匹配数据
         */
        String account =et_account.getText().toString();
        String pwd  = et_pwd.getText().toString();
        if(account.isEmpty()||pwd.isEmpty())
            Toast.makeText(this,"账号密码不可以为空！",Toast.LENGTH_LONG).show();
        else {
            //开启异步登录
            loginAsyncTask = new LoginAndRegisterAsyncTask();
            loginAsyncTask.setTaskType(LOGIN_TASK);
            loginAsyncTask.execute(0,account,pwd);
        }
    }

    public class LoginAndRegisterAsyncTask extends AsyncTask{
        private int taskType;
        private boolean isRegisterSuccess=false;

        @Override
        protected void onPreExecute() {
            bar = new ProgressDialog(MainActivity.this);
            bar.setMax(PROGRESS_MAXVALUE);
            if(taskType==LOGIN_TASK){
                bar.setTitle("用户登录");
                bar.setMessage("登录中....");
            }else if(taskType==REGISTER_TASK){
                bar.setTitle("用户注册");
                bar.setMessage("注册中....");
            }
            bar.setIndeterminate(false);
            bar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            bar.setCancelable(false);
            bar.show();
        }

        @Override
        protected Object doInBackground(Object[] objects) {

            if(isCancelled())
                return null;
            int progressStart = (Integer) objects[0];
            String account = (String) objects[1];
            String pwd = (String) objects[2];

            //模拟耗时任务，开启进度条
            this.progress(progressStart);

            if(taskType==LOGIN_TASK){
                cursor = sqLiteOpenHelper.getReadableDatabase().query("user",null,"account=? and password=?",new String[]{account,pwd},null,null,null);
                return taskType;
            }else if(taskType==REGISTER_TASK){
                cursor = sqLiteOpenHelper.getReadableDatabase().query("user",null,"account=?",new String[]{account},null,null,null);
                if(cursor.moveToFirst()){
                    return taskType;
                }
                ContentValues contentValues = new ContentValues();
                contentValues.put("account",account);
                contentValues.put("password",pwd);
                long result = sqLiteOpenHelper.getWritableDatabase().insert("user",null,contentValues);
                isRegisterSuccess = result!=-1 ? true:false;
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Object[] values) {
            /**
             * 更新进度条
             */
            int progress = (Integer)values[0];
            if(progress<PROGRESS_MAXVALUE){
                bar.setProgress(progress);
            }else if(progress==PROGRESS_MAXVALUE){
                bar.setProgress(PROGRESS_MAXVALUE);
                bar.dismiss();
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            if(taskType==LOGIN_TASK){
                if(cursor.moveToFirst()){
                    /**
                     * 登录成功
                     * 1、处理记住密码
                     * 2、保存用户信息
                     * 3、跳转到首页
                     */
                    //1、处理记住密码
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("remember_pwd",MODE_PRIVATE);
                            editor = sharedPreferences.edit();
                            if(cb_remenberPwd.isChecked()) {
                                editor.putString("account", et_account.getText().toString());
                                editor.putString("pwd", et_pwd.getText().toString());
                            }else{
                                editor.putString("account","");
                                editor.putString("pwd", "");
                            }
                            editor.commit();
                        }
                    }).start();

                    //2、保存用户信息
                    MyApplication.getApplication().setAccount(et_account.getText().toString());

                    //3、跳转到首页
                    Intent intent = new Intent(MainActivity.this,HomeActivity.class);
                    startActivity(intent);
                    Toast.makeText(MainActivity.this,"登录成功!",Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(MainActivity.this,"账号密码不正确！",Toast.LENGTH_LONG).show();
                }
                cursor = null;
                loginAsyncTask = null;
            }else if(taskType==REGISTER_TASK){
                if(cursor.moveToFirst()){
                    Toast.makeText(MainActivity.this,"账号已存在！",Toast.LENGTH_LONG).show();
                    return;
                }
                if(isRegisterSuccess){
                    Toast.makeText(MainActivity.this,"注册成功！",Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(MainActivity.this,"注册失败！",Toast.LENGTH_LONG).show();
                }
            }
        }

        private void progress(int progress){
            /**
             * 进度模拟，每5毫秒增加1%进度
             */
            while(progress<=PROGRESS_MAXVALUE){
                this.publishProgress(progress);
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e)
                {
                    Thread.currentThread().interrupt();
                }
                progress++;
            }
        }

        public void setTaskType(int taskType) {
            this.taskType = taskType;
        }
    }


}
